package com.sto.stoapp.db.manager;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.sto.stoapp.db.StoDataBase;
import com.sto.stoapp.entity.BaseEntity;
import com.sto.stoapp.entity.BillcodeEntity;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.util.UnifiedStaticType;

/**
 * 面单管理
 * 
 * @author cjb
 * 
 */

public class BillcodeManager extends StoDataBase {

	private static BillcodeManager manager;
	private static final String SQL_QUERY_CODE_BY_SIZE = "select "
			+ BILLCODE_BEGIN + "," + BILLCODE_END + " from " + BILLCODE_TABLE
			+ " where " + BILLCODE_BEGIN + "<=? and " + BILLCODE_END + ">=?";
	private static final String SQL_QUERY_COUNT = "select count(*) from "
			+ BILLCODE_TABLE + " where 1=1";
	private static final String SQL_QUERY_ALL = "select * from "
			+ BILLCODE_TABLE + " where 1=1";

	public BillcodeManager(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	/**
	 * 单例化对象
	 * 
	 * @param context
	 * @return
	 */
	public static BillcodeManager getInstance(Context context) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			if (manager == null) {
				manager = new BillcodeManager(context);
			}
			return manager;
		}
	}

	/**
	 * 查询面单的数量
	 * 
	 * @return
	 */
	public int queryAllCount() {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			int count = 0;
			Cursor cursor = getSqliteDatabase(UnifiedStaticType.READ_DATABASE)
					.rawQuery(SQL_QUERY_COUNT, null);
			if (cursor != null && cursor.moveToFirst()) {
				count = cursor.getInt(0);
			}
			closeCursor(cursor);
			closeDb(UnifiedStaticType.READ_DATABASE);
			return count;
		}
	}

	public List<BillcodeEntity> queryAll() {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			List<BillcodeEntity> entitys = new ArrayList<BillcodeEntity>();
			SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.READ_DATABASE);
			Cursor c = db.rawQuery(SQL_QUERY_ALL, null);
			if (c != null) {
				if (c.moveToFirst()) {
					do {
						BillcodeEntity entity = new BillcodeEntity();
						entity.setBillcodeBegin(c.getString(c
								.getColumnIndex(BILLCODE_BEGIN)));
						entity.setBillcodeEnd(c.getString(c
								.getColumnIndex(BILLCODE_END)));
						entity.setExtendDate(c.getString(c
								.getColumnIndex(EXTEND_DATE)));
						entity.setSiteName(c.getString(c
								.getColumnIndex(SITE_NAME)));
						entity.setReleaseQuantity(c.getString(c
								.getColumnIndex(RELEASE_QUANTITY)));
						entitys.add(entity);
					} while (c.moveToNext());
				}
				closeCursor(c);
			}
			closeDb(UnifiedStaticType.READ_DATABASE);
			return entitys;
		}
	}

	public boolean insert(BaseEntity entity) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			if (!(entity instanceof BillcodeEntity)) {
				return false;
			}
			BillcodeEntity billcodeEntity = (BillcodeEntity) entity;
			long res = -1;
			SQLiteDatabase sqlite = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
			try {
				ContentValues values = new ContentValues();
				values.put(EXTEND_DATE, billcodeEntity.getExtendDate());
				values.put(SITE_NAME, billcodeEntity.getSiteName());
				values.put(BILLCODE_BEGIN, billcodeEntity.getBillcodeBegin());
				values.put(BILLCODE_END, billcodeEntity.getBillcodeEnd());
				values.put(RELEASE_QUANTITY,
						billcodeEntity.getReleaseQuantity());
				res = sqlite.insert(BILLCODE_TABLE, null, values);
				if (res > 0) {
					Log.d("插入一条面单", "成功");
				} else {
					Log.d("插入一条面单", "失败");
				}
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("insert", e.getMessage());
			} finally {
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}
			return res == -1 ? false : true;
		}
	}

	/**
	 * 批量更新数据
	 * 
	 * @param datas
	 */
	public void insertList(List<BaseEntity> datas) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			int length = datas.size();
			SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
			try {
				db.beginTransaction();
				for (int i = 0; i < length; i++) {
					long res = -1;
					BillcodeEntity billcodeEntity = null;
					if (datas.get(i) instanceof BillcodeEntity) {
						billcodeEntity = (BillcodeEntity) datas.get(i);
					} else {
						continue;
					}
					ContentValues values = new ContentValues();
					values.put(EXTEND_DATE, billcodeEntity.getExtendDate());
					values.put(SITE_NAME, billcodeEntity.getSiteName());
					values.put(BILLCODE_BEGIN,
							billcodeEntity.getBillcodeBegin());
					values.put(BILLCODE_END, billcodeEntity.getBillcodeEnd());
					values.put(RELEASE_QUANTITY,
							billcodeEntity.getReleaseQuantity());
					res = db.insert(BILLCODE_TABLE, null, values);
					if (res > 0) {
						Log.d("插入一条面单", "成功");
					} else {
						Log.d("插入一条面单", "失败");
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("insertList", e.getMessage());
			} finally {
				datas.clear();
				db.setTransactionSuccessful();
				db.endTransaction();
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}
		}
	}

	/**
	 * 删除该数据库表所有数据
	 * 
	 * @return
	 */
	public boolean deleteAll() {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			long res = -1;
			try {
				res = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE)
						.delete(BILLCODE_TABLE, null, null);
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("deleteAll", e.getMessage());
			} finally {
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}
			return res > 0 ? true : false;
		}
	}

	/**
	 * 查询单号是否属于在面单发放记录里
	 * 
	 * @param code
	 * @return
	 */
	public boolean queryCodeBySize(String code) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			boolean isExist = false;
			SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.READ_DATABASE);
			try {
				Cursor cursor = db.rawQuery(SQL_QUERY_CODE_BY_SIZE,
						new String[] { code, code });
				if (cursor != null) {
					if (cursor.moveToFirst()) {
						isExist = true;
					}
					closeCursor(cursor);
				}
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("queryCodeBySize", e.getMessage());
			} finally {
				closeDb(UnifiedStaticType.READ_DATABASE);
			}
			return isExist;
		}
	}

}
